import requests
from lxml import etree

# 请求URL
url = '<https://www.qiushibaike.com/text/>'
# 请求头部
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}


# 解析页面函数
def parse_html(html):
    selector = etree.HTML(html)
    content_list = selector.xpath('//div[@class="content"]/span/text()')
    for content in content_list:
        yield content


# 保存数据函数
def save_data():
    f = open('qiushibaike_jokes.txt', 'w', encoding='utf-8')
    for i in range(3):
        url = '<https://www.qiushibaike.com/text/page/>' + str(i + 1) + '/'
        response = requests.get(url, headers=headers)
        html = response.text
        for content in parse_html(html):
            f.write(content + '\n')


if __name__ == '__main__':
    save_data()
